package com.woniu.teachmall04.controller;

import com.woniu.teachmall04.entity.Users;
import com.woniu.teachmall04.service.UserService;
import com.woniu.teachmall04.service.admin.AdminService;
import com.woniu.teachmall04.service.login.LoginStrategy;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private LoginStrategy  loginStrategy;
    //进入登录页面
    @GetMapping("/login")  //  user/login
    public String login() {
        return "login";
    }
    //进入注册页面
    @GetMapping("/register")  // user/register
    public String register() {
        return "register";
    }

    //登录
    @PostMapping("/login")
    public String login(@RequestParam("account") String account,
                        @RequestParam("password") String password,
                        HttpSession session) {
        Users user = loginStrategy.login(account, password);
        if(user == null){
            return "redirect:/user/login";
        }else{
            session.setAttribute("loginUser", user);
            return "redirect:/";
        }
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadAvatar(MultipartFile file) throws Exception {
        String url = userService.uplaodAvatar(file);
        return ResponseEntity.ok(url);
    }


    //登录退出
    @GetMapping("/logout")  // /user/logout
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");//删除数据
        return "redirect:/user/login";
    }



    //注册功能
    @PostMapping("/register")
    @ResponseBody
    public String register(@RequestParam String account,
                           @RequestParam String password,
                           @RequestParam String email,
                           @RequestParam String telphone,
                           @RequestParam String url) throws Exception {
        //如果注册成功，返回登录页面，否则还是停留在注册页面
        boolean re = userService.insertUser(account,password,email,telphone,url);
        if(re){
            //重定向到其他的页面
            return "success";
        }else{
            return "fail";
        }
    }
}
